import { ErrorCode } from "../config/ErrorCode";
import { ServerConfig } from "../config/ServerConfig";
import HttpUtil from "../engine/HttpUtil";
import { JhaoEncrypt } from "../engine/JHaoEncrypt";
import { Logger } from "../engine/Logger";
import { Md5Helper } from "../engine/Md5Helper";
import ServerTimer from "../engine/ServerTimer";
import { UIManager } from "../engine/UIManager";
import VersionManager from "../engine/VersionManager";
import { NativeSdkHelper } from "../sdk/NativeSdkHelper";

export class HttpController {

    private static _instance: HttpController;
    public static get instance(): HttpController {
        if (!HttpController._instance) {
            HttpController._instance = new HttpController();
        }
        return HttpController._instance;
    }

    public static getInitConfig(callback: Function) {
        UIManager.instance.showLoadingIcon()
        let http: HttpUtil = new HttpUtil();
        let url: string = ServerConfig.getWebServerUrl() + "/login_jhao"
        let data: object = {
            "t": ServerTimer.now,
            "channel": NativeSdkHelper.channel,
            "v": VersionManager.instance.nowVersion
        }
        let param: object = {
            "k": Md5Helper.getMd5_encrypt(JSON.stringify(data)),
            "data": data
        }
        http.setMethod(HttpUtil.methodTypeOption.POST)
        http.requestByBody(url, (isOK: boolean, response: any) => {
            UIManager.instance.hideLoadingIcon()
            if (isOK) {
                if (response) {
                    let code: number = response["code"];
                    if (code == ErrorCode.Code.Suc) {
                        let data: string = response["data"]
                        let jhaoStr: string = JhaoEncrypt.decode(data)
                        interface json {
                            anroid_url: string;
                            ios_url: string;
                            force_update: boolean;
                            need_hotupdate: boolean
                        }
                        let objVersion: json = JSON.parse(jhaoStr);
                        ServerConfig.initAccountServer(objVersion)
                        VersionManager.instance.apkStoreUrl = objVersion.anroid_url;
                        VersionManager.instance.iosStoreUrl = objVersion.ios_url;
                        let force_update: boolean = objVersion["force_update"]
                        let need_hotupdate: boolean = objVersion["need_hotupdate"];
                        Logger.log("getInitConfig=", objVersion)
                        if (force_update) {
                            VersionManager.instance.jumpToPackUpate()
                        } else {
                            callback(need_hotupdate)
                        }
                    } else {
                        callback(false)
                    }
                } else {

                }
            }
        }, JSON.stringify(param));
    }

}